"""
应用程序引导

初始化依赖注入容器和核心服务。
"""

import logging
import sys
from pathlib import Path

# 添加项目根目录到Python路径
current_dir = Path(__file__).parent
project_root = current_dir.parent
sys.path.insert(0, str(project_root))

from src.core.di import injector
from src.services import ConfigService, config_service, FFmpegService, FfmpegSliceService
from src.modules.processors import FFmpegProcessor
from src.modules.analyzers import OpenCVAnalyzer
from src.services.opencv_service import OpenCVService

def setup_logging(config_service: ConfigService) -> logging.Logger:
    """设置日志系统"""
    log_config = config_service.get_section("logging")
    
    # 创建日志目录
    log_file = log_config.get("file", "./logs/mixvideo.log")
    log_path = Path(log_file)
    log_path.parent.mkdir(parents=True, exist_ok=True)
    
    # 配置日志格式 - 使用标准Python logging格式
    log_format = log_config.get("format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # 如果配置文件中使用了loguru风格的格式，转换为标准格式
    if "{time:" in log_format:
        log_format = "%(asctime)s | %(levelname)s | %(name)s:%(funcName)s:%(lineno)d | %(message)s"
    log_level = getattr(logging, log_config.get("level", "INFO").upper())
    
    # 配置根日志器
    logging.basicConfig(
        level=log_level,
        format=log_format,
        handlers=[
            logging.FileHandler(log_file, encoding='utf-8'),
            logging.StreamHandler(sys.stdout)
        ]
    )
    
    logger = logging.getLogger("MixVideo")
    return logger


def register_core_services() -> None:
    """注册核心服务到依赖注入容器"""
    
    # 注册配置服务
    injector.bind_value("config", config_service.get_all())
    injector.bind_value(ConfigService, config_service)
    
    # 设置日志
    logger = setup_logging(config_service)
    injector.bind_value("logger", logger)
    injector.bind_value(logging.Logger, logger)
    
    # 注册FFmpeg相关服务
    injector.bind_class(FFmpegProcessor, FFmpegProcessor, scope="singleton")
    injector.bind_class(FFmpegService, FFmpegService, scope="singleton")
    injector.bind_class(FfmpegSliceService, FfmpegSliceService, scope="singleton")

    # 注册OpenCV相关服务
    injector.bind_class(OpenCVAnalyzer, OpenCVAnalyzer, scope="singleton")
    injector.bind_class(OpenCVService, OpenCVService, scope="singleton")

    # 注册视频处理相关服务
    from src.services.shot_detection_service import ShotDetectionService
    from src.services.video_segmentation_service import VideoSegmentationService

    injector.bind_class(ShotDetectionService, ShotDetectionService, scope="singleton")
    injector.bind_class(VideoSegmentationService, VideoSegmentationService, scope="singleton")

    # 注册元数据提取器
    from src.modules.extractors import (
        FFmpegMetadataExtractor,
        OpenCVMetadataExtractor,
        CompositeMetadataExtractor
    )
    from src.services.metadata_service import MetadataService

    injector.bind_class(FFmpegMetadataExtractor, FFmpegMetadataExtractor, scope="singleton")
    injector.bind_class(OpenCVMetadataExtractor, OpenCVMetadataExtractor, scope="singleton")
    injector.bind_class(CompositeMetadataExtractor, CompositeMetadataExtractor, scope="singleton")
    injector.bind_class(MetadataService, MetadataService, scope="singleton")

    # 注册目录扫描相关服务
    from src.modules.scanners import (
        MediaDirectoryScanner,
        MediaFileClassifier,
        SmartFileClassifier,
        FileManager
    )
    from src.services.directory_service import DirectoryService

    injector.bind_class(MediaDirectoryScanner, MediaDirectoryScanner, scope="singleton")
    injector.bind_class(MediaFileClassifier, MediaFileClassifier, scope="singleton")
    injector.bind_class(SmartFileClassifier, SmartFileClassifier, scope="singleton")
    injector.bind_class(FileManager, FileManager, scope="singleton")
    injector.bind_class(DirectoryService, DirectoryService, scope="singleton")

    # 注册AI分类相关服务
    from src.services.gemini_service import GeminiService
    from src.services.mock_gemini_service import MockGeminiService
    from src.modules.classifiers import (
        GeminiVideoClassifier,
        HybridClassifier,
        AdvancedAIClassifier,
        ClassificationPerformanceEvaluator
    )
    from src.services.classification_service import ClassificationService

    injector.bind_class(GeminiService, GeminiService, scope="singleton")
    injector.bind_class(MockGeminiService, MockGeminiService, scope="singleton")
    injector.bind_class(GeminiVideoClassifier, GeminiVideoClassifier, scope="singleton")
    injector.bind_class(HybridClassifier, HybridClassifier, scope="singleton")
    injector.bind_class(AdvancedAIClassifier, AdvancedAIClassifier, scope="singleton")

    # 注册剪映草稿服务
    from src.services.jianying_draft_service import JianyingDraftService
    from src.services.jianying_template_analyzer import JianyingTemplateAnalyzer
    from src.services.jianying_template_scanner import JianyingTemplateScanner
    from src.services.material_workflow_database_service import MaterialWorkflowDatabaseService
    injector.bind_class(JianyingDraftService, JianyingDraftService, scope="singleton")
    injector.bind_class(JianyingTemplateAnalyzer, JianyingTemplateAnalyzer, scope="singleton")
    injector.bind_class(JianyingTemplateScanner, JianyingTemplateScanner, scope="singleton")
    injector.bind_class(MaterialWorkflowDatabaseService, MaterialWorkflowDatabaseService, scope="singleton")
    injector.bind_class(ClassificationPerformanceEvaluator, ClassificationPerformanceEvaluator, scope="singleton")
    injector.bind_class(ClassificationService, ClassificationService, scope="singleton")

    # 注册数据库相关服务
    from src.database import DatabaseManager, MigrationManager
    from src.repositories import VideoRepository, TaskRepository, ProjectRepository, JianyingTemplateRepository, JianyingVideoSegmentRepository
    from src.services.data_service import DataService

    # 先注册数据库管理器
    injector.bind_class(DatabaseManager, DatabaseManager, scope="singleton")
    injector.bind_class(MigrationManager, MigrationManager, scope="singleton")

    # 初始化数据库管理器
    db_manager = injector.get(DatabaseManager)
    migration_manager = injector.get(MigrationManager)

    # 执行数据库迁移
    migration_result = migration_manager.migrate_to_latest(db_manager.engine)
    if migration_result['success']:
        ...
    else:
        logger.error(f"数据库迁移失败: {migration_result.get('error', 'unknown')}")

    # 然后注册仓库和服务
    injector.bind_class(VideoRepository, VideoRepository, scope="singleton")
    injector.bind_class(TaskRepository, TaskRepository, scope="singleton")
    injector.bind_class(ProjectRepository, ProjectRepository, scope="singleton")
    injector.bind_class(JianyingTemplateRepository, JianyingTemplateRepository, scope="singleton")
    injector.bind_class(JianyingVideoSegmentRepository, JianyingVideoSegmentRepository, scope="singleton")
    injector.bind_class(DataService, DataService, scope="singleton")


def load_configuration() -> None:
    """加载应用程序配置"""
    
    # 加载配置文件
    config_files = [
        "./config/config.yaml",
        "./config.yaml",
        "./mixvideo.yaml"
    ]
    
    for config_file in config_files:
        if Path(config_file).exists():
            config_service.load_from_file(config_file)
            break
    
    # 加载环境变量
    config_service.load_from_env("MIXVIDEO_")
    
    # 验证配置
    errors = config_service.validate_config()
    if errors:
        print("配置验证失败:")
        for error in errors:
            print(f"  - {error}")
        sys.exit(1)
    
    # 创建必要的目录
    config_service.create_directories()


async def initialize_plugins() -> None:
    """初始化插件系统"""
    from src.core.plugin import plugin_manager

    logger = logging.getLogger("MixVideo")

    try:
        # 获取插件目录
        plugins_dir = config_service.get("storage.plugins_dir", "./plugins")

        # 初始化插件管理器
        await plugin_manager.initialize()

        # 加载插件目录中的插件
        if Path(plugins_dir).exists():
            await plugin_manager.load_plugins_from_directory(plugins_dir)
        else:
            logger.info(f"插件目录不存在: {plugins_dir}")

    except Exception as e:
        logger.error(f"插件初始化失败: {e}")
        raise


async def bootstrap_application() -> None:
    """引导应用程序"""

    # 1. 加载配置
    load_configuration()

    # 2. 注册核心服务
    register_core_services()

    # 3. 初始化插件
    await initialize_plugins()

def get_service(service_type):
    """获取服务实例的便捷函数"""
    return injector.get(service_type)


async def shutdown_application() -> None:
    """关闭应用程序"""
    logger = logging.getLogger("MixVideo")

    try:
        # 关闭插件管理器
        from src.core.plugin import plugin_manager
        await plugin_manager.shutdown()
    except Exception as e:
        logger.error(f"插件管理器关闭失败: {e}")

    try:
        # 清理依赖注入容器
        injector.clear()
    except Exception as e:
        logger.error(f"依赖注入容器清理失败: {e}")

if __name__ == "__main__":
    import asyncio
    asyncio.run(bootstrap_application())
